package com.lwg.datastructure.CommonSelectMethod;

/**
 * @author: lwg
 * @Date: 2022/4/24 18:00
 * @Description: 哈希查找
 */
public class HashSearch {
    public static void main(String[] args) {
        // 首先构建hash数组值
        int arr[] = {2, 8, 3, 7, 1, 21, 36, 17};
        int hashLength = 30;
        int[] hashArr = new int[hashLength];
        for (int i = 0; i < arr.length; i++) {
            insertHash(hashArr, arr[i]);
        }
        for (int i = 50; i > 0; i--) {
            int index = searchSearch(hashArr, hashLength, i);
            if (index != -1) {
                System.out.println("原数组中有" + i + "这个元素");
            }
        }
    }
    
    private static int searchSearch(int[] hashArr, int hashLength, int key) {
        int index = key % hashLength;
        while (hashArr[index] != 0 && hashArr[index] != key) {
            index = (++index) % hashLength;
        }
        if (hashArr[index] == 0) {
            return -1;
        }
        return index;
    }
    
    private static void insertHash(int[] hashArr, int data) {
        int index = data % hashArr.length;
        while (hashArr[index] != 0) {
            index = (++index) % hashArr.length;
        }
        hashArr[index] = data;
    }
}
